﻿using DataImporter.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DataImporter.Modules
{
    public partial class ucTF : UserControl
    {
        public ucTF()
        {
            InitializeComponent();
            this.cbbDropdown.SelectedIndex = 0;
        }

        private DBContext DBContext => new DBContext();

        private void ofdFile_FileOk(object sender, CancelEventArgs e)
        {
            var table = this.ofdFile.FileName.GetDataTable(this.cbbDropdown.SelectedItem.ToString());
            if (this.cbbDropdown.SelectedIndex == 0)
                HandleFirst(table);
        }

        private void HandleFirst(DataTable table)
        {
            var risks = new List<GoutRisk>();
            int order = 0;
            for (int i = 5; i < table.Rows.Count; i++)
            {
                var row = table.Rows[i];
                var rule = row[5].ToString();

                if (rule.IsNullOrEmpty())
                    break;

                risks.Add(new GoutRisk
                {
                    Name = row[1].ToString(),
                    MaleAverage = float.Parse(row[8].ToString()),
                    MaleRiseNumber = float.Parse(row[9].ToString()),
                    MaleAge = float.Parse(row[12].ToString()),
                    FemaleAverage = float.Parse(row[16].ToString()),
                    FemaleRiseNumber = float.Parse(row[17].ToString()),
                    FemaleAge = float.Parse(row[20].ToString()),
                    Rule = rule,
                    Order = order += 5
                });
            }

            this.dgvData.DataSource = risks;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            this.ofdFile.ShowDialog();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.cbbDropdown.SelectedIndex == 0)
            {
                if (!DBContext.Db.DbMaintenance.IsAnyTable(nameof(GoutRisk)))
                    DBContext.Db.CodeFirst.InitTables<GoutRisk>();
                DBContext.Db.DbMaintenance.TruncateTable<GoutRisk>();
                DBContext.GoutRiskDB.InsertRange((List<GoutRisk>)this.dgvData.DataSource);
            }
            MessageBox.Show("保存成功");
        }
    }
}
